﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNet.Model;
using System.Data;
using System.Text;
using NBear.Mapping;
//using KingRoad.EPM.InvestmeEntity;
using KingRoad.EPM.Common.Helper;
using DotNet.Utilities;
using MySoft.Data;
using MySoft;
using DotNet.Service;
using DotNet.Model.MyEntity;
using System.IO;
using System.Net;
using KingRoad.EPM.Web.ViewModels;
using WebUtility = KingRoad.EPM.Web.Util.WebUtility;

namespace KingRoad.EPM.Web.Areas.Permission.Controllers
{
	public class UserController : Controller
	{
		/// <summary>
		/// 用户管理
		/// 功能描述：用户的增、删、改、查及用户的授权、关联角色等等。
		/// 模块负责人：张雨
		/// 完成日期：2011.9.23
		/// 修改：去除职员，直接在组织机构中添加用户 WS 2013.5.9
		/// </summary>
		public ActionResult Index()
		{
			//修改为接收公司主键、部门主键、岗位主键并传给前端
			//部门名称、岗位名称也传递过来 WS 2011.10.24
			if (!String.IsNullOrEmpty(Request["dutyId"]))
			{
				string dutyId = Request["dutyId"].Substring(2);
				int indexP = dutyId.IndexOf('_');
				ViewBag.DutyId = dutyId.Substring(0, dutyId.Length - indexP - 1);
				ViewBag.DutyName = Request["dutyName"];
			}
			if (!String.IsNullOrEmpty(Request["departId"]))
				ViewBag.DepartId = Request["departId"].Substring(2);
			ViewBag.DepartName = Request["departName"];
			if (!String.IsNullOrEmpty(Request["companyId"]))
			{
				ViewBag.CompanyId = Request["companyId"].Substring(2);
				ViewBag.CompanyName = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(Request["companyId"].Substring(2)).FullName;
			}

			return View();
		}

		/// <summary>
		/// 添加用户
		/// 修改：添加时参数传递 WS 2013.5.11
		/// </summary>
		/// <returns></returns>
		public ActionResult AddUser(int companyId, int departId, int dutyId)
		{
			//默认角色改为列表选择
			//List<Base_Role> list = ServiceManager.Instance.RoleService.GetDT();
			//ViewBag.list = list;
			ViewBag.CompanyId = companyId;
			ViewBag.DepartId = departId;
			ViewBag.DutyId = dutyId;
			ViewBag.DepartName = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(departId.ToString()).FullName;
			ViewBag.DutyName = ServiceManager.Instance.OrganizeService.GetDutyEntityById(dutyId.ToString()).Name;
			ViewBag.CompanyName = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(companyId.ToString()).FullName;
			ViewBag.Titles = ServiceManager.Instance.ItemDetailsService.GetItemsByCode("Title");
			ViewBag.Gender = ServiceManager.Instance.ItemDetailsService.GetItemsByCode("Gender");
			List<BaseItemDetailsEntity> list = ServiceManager.Instance.ItemsService.GetTiemDetailsDT("Items_DutyList");
			ViewBag.DutyList = list ?? new List<BaseItemDetailsEntity>();
			return View();
		}

		/// <summary>
		/// 对用户实现批量删除操作
		/// </summary>
		/// <returns></returns>
		public ActionResult Delete()
		{
			int state = 1;
			string UserArryID = Request.Form["UserArryID"];
			if (!string.IsNullOrEmpty(UserArryID))
			{
				if (UserArryID.LastIndexOf(',') == UserArryID.Length - 1)
				{
					UserArryID = UserArryID.Substring(0, UserArryID.Length - 1);
				}
				if (ServiceManager.Instance.UserService.BatchDeleteUser(UserArryID) > 0)
				{
					state = 0;
				}
			}

			return Json(new CallbackStatus
			{
				message = state == 0 ? "操作成功！" : "操作失败",
				statusCode = state == 0 ? "200" : "300",
				callbackType = "closeCurrent"
			});
			//return Json(state);
		}

		/// <summary>
		/// 用户的编辑 WS 
		/// 修改：此功能去除 2011.11.30
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult Detail(int id)
		{

			//List<Base_Role> list = ServiceManager.Instance.RoleService.GetDT();
			//ViewBag.list = list;

			Base_User user = ServiceManager.Instance.UserService.GetUserEntityByID(id);

			return View(user);
		}

		/// <summary>
		/// 用户的添加操作
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		[HttpPost]
		public ActionResult UserAdded(Base_User user)
		{
			//添加用户并添加关系
			string statuCode = string.Empty;
			string statuMessage = string.Empty;
			//if (ModelState.IsValid)//实体验证
			//{
			if (Request["UserName"] == null || Request["UserPassword"] == null || Request["tUserPassword"] == null)
			{
				return Json(new CallbackStatus
				{
					message = "请填写用户名或密码!",
					statusCode = "300",
					callbackType = "Create",
					data = user
				});
			}
			System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9_]{2,}$");
			if (!regex.IsMatch(Request["UserName"].Trim()))
			{
				return Json(new CallbackStatus
				{
					message = "用户名格式不正确，请以英文、数字做用户名，并且最小4位！",
					statusCode = "300",
					callbackType = "Create",
					data = user
				});
			}
			if (Request["tUserPassword"].Trim() != Request["UserPassword"].Trim())
			{
				return Json(new CallbackStatus
				{
					message = "两次输入的密码不一致！",
					statusCode = "300",
					callbackType = "Create",
					data = user
				});
			}
			if (ServiceManager.Instance.UserService.Exists(Request["UserName"]))
			{
				return Json(new CallbackStatus
				{
					message = "已经存在同名用户!",
					statusCode = "300",
					callbackType = "Create",
					data = user
				});
			}

			//添加用户
			user.DeletionStateCode = 0;
			try
			{
				string id = ServiceManager.Instance.UserService.AddUser(user, out statuCode, out statuMessage);
				if (!string.IsNullOrWhiteSpace(id))
				{
					user.Id = Convert.ToInt32(id);
					if (statuCode == StatusCode.OKAdd.ToString())
					{
						//同时创建关系
						Base_OrgDutyUser odu = new Base_OrgDutyUser();
						odu.DutyID = int.Parse(Request["dutyId"].ToString());
						if (user.DepartmentId.HasValue)
							odu.OrganizeID = user.DepartmentId;
						else
							odu.OrganizeID = user.CompanyId;
						odu.UserID = user.Id;
						ServiceManager.Instance.OrganizeService.CreateConnectionDutyAndStaff(odu.DutyID.ToString(), odu.UserID.ToString(), odu.OrganizeID.ToString(), out statuCode, out statuMessage);
						if (!String.IsNullOrEmpty(Request["RoleIDs"]))
						{
							string userStatusCode = string.Empty, userStatusMsg = string.Empty;
							//添加该用户的所选角色
							ServiceManager.Instance.UserService.AddUserToRole(odu.UserID.ToString(), Request["RoleIDs"], out userStatusCode, out userStatusMsg);
						}
					}
				}
			}
			catch (Exception ex)
			{
				statuMessage = ex.Message;
				statuCode = "300";
			}

			//}
			return Json(new CallbackStatus
			{
				message = statuMessage,
				statusCode = statuCode,
				callbackType = statuCode == "200" ? "closeCurrent" : "create",
				data = user
			});
		}

		/// <summary>
		/// 用户的编辑 WS 
		/// 修改：此功能去除 2011.11.30
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult UserEdit(int id)
		{

			//List<Base_Role> list = ServiceManager.Instance.RoleService.GetDT();
			//ViewBag.list = list;

			Base_User user = ServiceManager.Instance.UserService.GetUserEntityByID(id);

			string[] roleListIDs = ServiceManager.Instance.UserService.GetUserRoleIds(id.ToString());
			string roleListID = StringHelper.listToString(roleListIDs);//角色ID列表
			ViewData["roleListID"] = roleListID;
			string RoleNames = String.Empty;
			if (roleListID.Length > 0)
			{
				for (int i = 0; i < roleListIDs.Count(); i++)
				{
					RoleNames += ServiceManager.Instance.RoleService.GetRoleEntityByID(roleListIDs[i]).Realname + ",";
				}
				RoleNames = RoleNames.Substring(0, RoleNames.Length - 1);
			}
			ViewBag.RoleNames = RoleNames;
			ViewBag.Titles = ServiceManager.Instance.ItemDetailsService.GetItemsByCode("Title");
			ViewBag.Gender = ServiceManager.Instance.ItemDetailsService.GetItemsByCode("Gender");
			List<BaseItemDetailsEntity> list = ServiceManager.Instance.ItemsService.GetTiemDetailsDT("Items_DutyList");
			ViewBag.DutyList = list ?? new List<BaseItemDetailsEntity>();
			return View(user);
		}

		/// <summary>
		/// 修改的执行事件 WS 
		/// 修改：去除此功能 2011.11.31
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		[HttpPost]
		public ActionResult UserEdited(Base_User user)
		{
			string outCode = string.Empty, outMessage = string.Empty;//返回状态码，返回信息
			//if (ModelState.IsValid)//实体验证
			//{
			//只修改是否禁用与姓名 WS 2012.1.12
			Base_User detail = ServiceManager.Instance.UserService.GetUserEntityByID(user.Id);
			detail.Enabled = user.Enabled;
			detail.RealName = user.RealName;
			detail.SortCode = user.SortCode;
			detail.Title = user.Title;
			detail.Email = user.Email;
			detail.Mobile = user.Mobile;
			detail.ModifiedBy = UserService.CurrUserInfo.UserName;
			detail.ModifiedOn = DateTime.Now;
			detail.ModifiedUserId = UserService.CurrUserInfo.Id;
			detail.OICQ = user.OICQ;
			detail.HomeAddress = user.HomeAddress;
			detail.DutyOrderId = user.DutyOrderId;
			detail.DutyOrderName = user.DutyOrderName;
			ServiceManager.Instance.UserService.UpdateUser(detail, out outCode, out outMessage);
			if (outCode == DotNet.Utilities.StatusCode.OKUpdate.ToString())
			{
				//同时修改职员姓名
				//Base_Staff staffDetail = ServiceManager.Instance.OrganizeService.GetStaffByUserName(detail.UserName);
				//if (staffDetail != null)
				//{
				//    string staffOutCode = string.Empty, staffOutMsg = string.Empty;
				//    staffDetail.RealName = user.RealName;
				//    ServiceManager.Instance.OrganizeService.EditStaff(staffDetail, out staffOutCode, out staffOutMsg);
				//}
			}
			//去除 WS 2012.1.12
			//修改改用户的角色 全删全添 WS 2011.11.29
			//if (outCode == DotNet.Utilities.StatusCode.OKUpdate.ToString())
			//{
			//    if (!String.IsNullOrEmpty(Request["RoleIDs"]))
			//    {
			//        string userStatusCode = string.Empty, userStatusMsg = string.Empty;
			//        string[] rolelist = UserService.GetUserRoleIds(user.Id.ToString());//获取该用户所属的角色
			//        UserService.RemoveUserFromRole(user.Id.ToString(), StringHelper.listToString(rolelist), out userStatusCode, out userStatusMsg);
			//        UserService.AddUserToRole(user.Id.ToString(), Request["RoleIDs"], out userStatusCode, out userStatusMsg);
			//    }
			//}
			//}
			return Json(new CallbackStatus
			{
				message = outMessage,
				statusCode = outCode.ToLower() == "okupdate" ? "200" : "300",
				callbackType = "closeCurrent"
			});
		}

		/// <summary>
		/// 修改密码 去除原有的修改用户功能 WS 2011.11.30
		/// </summary>
		/// <param name="userName"></param>
		/// <param name="pwd"></param>
		/// <returns></returns>
		public ActionResult ChangePwd()
		{
			string userID = UserService.CurrUserInfo.Id;
			int id = 0;
			int.TryParse(userID, out id);
			Base_User Entity = new Base_User();
			if (id > 0)
				Entity.Id = id;
			return View(Entity);
		}
		/// <summary>
		/// 修改密码 管理员修改密码
		/// </summary>
		/// <param name="userName"></param>
		/// <param name="pwd"></param>
		/// <returns></returns>
		public ActionResult UserEditPwd(int id)
		{
			Base_User Entity = new Base_User();
			if (id > 0)
				Entity.Id = id;
			return View(Entity);
		}

		/// <summary>
		/// 管理员给账号重置密码
		/// </summary>
		/// <param name="Entity"></param>
		/// <returns></returns>
		public ActionResult UserEditingPwd(Base_User Entity)
		{
			string stateCode = "300";
			string Message = "修改密码失败";
			if (Entity.UserPassword != Entity.tUserPassword)
				Message = "新密码和确认密码不一致！";
			else
			{
				ServiceManager.Instance.UserService.SetPassword(Entity.Id.ToString(), Entity.UserPassword, out stateCode, out Message);
                if (stateCode == StatusCode.SetPasswordOK.ToString())
                {
                    stateCode = "200";
                    Message = "设置密码成功！";
                    Entity.UserPassword = new DotNet.Manager.BaseUserManager().EncryptUserPassword(Entity.UserPassword);
                    KingRoad.EPM.Common.Helper.HttpHelper.PostReqest(KingRoad.EPM.Common.Configuration.Settings.Instance.OAWebPath + "SetPwding", "UId=" + Entity.Id + "&UserPassword=" + Entity.UserPassword + "&confirmPassWord=" + Entity.UserPassword);
                }
			}
			return Json(new CallbackStatus
			{
				message = Message,
				statusCode = stateCode,
				callbackType = "closeCurrent",
                data = Entity
			});
		}
       

		/// <summary>
		/// 新设密码 WS 2011.11.30
		/// </summary>
		/// <param name="userID"></param>
		/// <param name="pwd"></param>
		/// <param name="comfirmPwd"></param>
		/// <returns></returns>
		public ActionResult ChangePwding(Base_User Entity)
		{
			string stateCode = "300";
			string Message = "修改密码失败";
			//Base_User UserEntity = UserCenter.UserService.GetUserEntityByID(Convert.ToInt32(Entity.Id));
			//if (UserEntity != null)
			//{
			//if (UserEntity.UserPassword !=UserCenter.UserService.ChangePassword(Entity.UserOldPassword))
			//{
			//    Message = "原始密码不正确！";
			//}
			//else
			//{
			if (Entity.UserPassword != Entity.tUserPassword)
				Message = "新密码和确认密码不一致！";
			else
			{
			    Entity.UserName = DotNet.Service.UserService.CurrUserInfo.UserName;
				ServiceManager.Instance.UserService.ChangePassword(Entity.UserOldPassword, Entity.UserPassword, out stateCode, out Message);
                if (stateCode == StatusCode.ChangePasswordOK.ToString())
                {
                    stateCode = "200";
                    Message = "修改密码成功！";
                    Entity.UserOldPassword =new DotNet.Manager.BaseUserManager().EncryptUserPassword(Entity.UserOldPassword);
                    Entity.UserPassword = new DotNet.Manager.BaseUserManager().EncryptUserPassword(Entity.UserPassword);
                    KingRoad.EPM.Common.Helper.HttpHelper.PostReqest(KingRoad.EPM.Common.Configuration.Settings.Instance.OAWebPath + "ChangePwding", "UserName=" + Entity.UserName + "&OldPassword=" + Entity.UserOldPassword + "&NewPassword=" + Entity.UserPassword + "&confirmPassWord=" + Entity.UserPassword);
                }

				//Message = stateCode == "200" ? "修改密码成功！" : "修改密码失败！";
			}
			//}
			//}
			return Json(new CallbackStatus
			{
				message = Message,
				statusCode = stateCode,
				callbackType = "closeCurrent",
                data = Entity
			});
		}

		/// <summary>
		/// 分页查询用户列表
		/// </summary>
		/// <returns></returns>
		public ActionResult GetUserByPage(QueryBase query, int departId, int dutyId)
		{
			//TODO:l将来更改为分页与数据权限 WS 2013.5.11
			//获取该部门该岗位下的所有人员
			var users = (ServiceManager.Instance.OrganizeService.GetUsersByDepartAndDuty(departId, dutyId) ?? new List<Base_User>()) as List<Base_User>;
			//if (users != null && users.Count > 0)
			//{
			//    users.ForEach(x =>
			//    {
			//        x.RoleName = (ServiceManager.Instance.UserService.GetDTByUserName(x.UserName) ?? new Base_User()).RoleName;
			//    });
			//}
			users = users.OrderBy(m => m.SortCode).ToList();
			query.total = users.Count;
			var jqGridData = WebUtility.TojqGridData(users, query);
			return Json(jqGridData);
		}

		/// <summary>
		/// 用户关联角色
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult linkRoles(string id)
		{
			int tempID = 0;
			if (!string.IsNullOrEmpty(id) && int.TryParse(id, out tempID))
			{
				ViewBag.userID = id;
				ViewBag.userName = ServiceManager.Instance.UserService.GetUserEntityByID(tempID).UserName;
				ViewData["roleListID"] = listToString(ServiceManager.Instance.UserService.GetUserRoleIds(id));
			}
			else
			{
				ViewBag.userID = string.Empty;
			}
			return View();
		}

		/// <summary>
		/// 设置用户关联角色
		/// </summary>
		/// <returns></returns>
		public ActionResult SetlinkRoles()
		{
			string state = "300", message = "角色用户关联失败！";
			//全局参数
			string userID = string.Empty, roleListID = string.Empty;
			userID = Request.Params["userID"];
			if (!string.IsNullOrEmpty(userID))
			{
				roleListID = Request.Params["roleIDs"];
				if (roleListID == null)
					roleListID = string.Empty;
				if (roleListID.EndsWith(","))
					roleListID = roleListID.Substring(0, roleListID.Length - 1);
				string[] rolelist = ServiceManager.Instance.UserService.GetUserRoleIds(userID);//获取该用户所属的角色               
				if (rolelist == null || rolelist.Length == 0 && roleListID != string.Empty)
				{
					ServiceManager.Instance.UserService.AddUserToRole(userID, roleListID, out state, out message);
				}
				else if (roleListID == string.Empty && rolelist.Length > 0)
				{
					ServiceManager.Instance.UserService.RemoveUserFromRole(userID, listToString(rolelist), out state, out message);
				}
				else if (roleListID == string.Empty && rolelist.Length == 0)
				{
					state = "200";
					message = "角色关联成功！";
				}
				else
				{
					string templist = string.Empty;
					string[] tempRoleList = roleListID.Split(',');
					//以原角色为参照，比对现有角色
					for (int i = 0; i < tempRoleList.Length; i++)
					{
						if (!rolelist.Contains(tempRoleList[i]))
						{
							templist += tempRoleList[i] + ",";
						}
					}
					if (templist.EndsWith(","))
						templist = templist.Substring(0, templist.Length - 1);
					//将新增的角色添加到用户中去
					if (templist != string.Empty)
					{
						ServiceManager.Instance.UserService.AddUserToRole(userID, templist, out state, out message);
					}

					templist = string.Empty;

					for (int i = 0; i < rolelist.Length; i++)
					{
						if (!tempRoleList.Contains(rolelist[i]))
						{
							templist += rolelist[i] + ",";
						}
					}
					//移除取消的角色
					if (templist != string.Empty)
					{
						ServiceManager.Instance.UserService.RemoveUserFromRole(userID, templist, out state, out message);
					}
				}
			}
			return Json(new CallbackStatus
			{
				message = message,
				statusCode = state,
				callbackType = "closeCurrent"
			});
		}

		/// <summary>
		/// 分配菜单访问权限
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult selectModule(string id)
		{
			int tempID = 0;
			if (!string.IsNullOrEmpty(id) && int.TryParse(id, out tempID))
			{
				ViewBag.userID = id;
				ViewBag.userName = ServiceManager.Instance.UserService.GetUserEntityByID(tempID).UserName;
				ViewData["moduleListID"] = listToString(ServiceManager.Instance.UserService.GetUserScopeModuleIds(id));
			}
			else
			{
				ViewBag.userID = string.Empty;
			}
			return View();
		}

		/// <summary>
		/// 设置用户菜单访问权限
		/// </summary>
		/// <returns></returns>
		public ActionResult SetselectModule()
		{
			string state = "300", message = "设置用户菜单访问权限失败！";
			//全局参数
			string userID = string.Empty, ModuleListID = string.Empty;
			userID = Request.Params["userID"];
			if (!string.IsNullOrEmpty(userID))
			{
				ModuleListID = Request.Params["moduleIDs"];
				if (ModuleListID == null)
					ModuleListID = string.Empty;
				if (ModuleListID.EndsWith(","))
					ModuleListID = ModuleListID.Substring(0, ModuleListID.Length - 1);
				string[] moduleList = ServiceManager.Instance.UserService.GetUserScopeModuleIds(userID);//获取该用户所拥有的菜单访问权限               
				if (moduleList == null || moduleList.Length == 0 && ModuleListID != string.Empty)
				{
					ServiceManager.Instance.UserService.GrantUserModuleScopes(userID, ModuleListID, out state, out message);
				}
				else if (ModuleListID == string.Empty && moduleList.Length > 0)
				{
					ServiceManager.Instance.UserService.RevokeUserModuleScopes(userID, listToString(moduleList), out state, out message);
				}
				else
				{
					string templist = string.Empty;
					string[] tempModuleList = ModuleListID.Split(',');
					//以原角色为参照，比对现有角色
					for (int i = 0; i < tempModuleList.Length; i++)
					{
						if (!moduleList.Contains(tempModuleList[i]))
						{
							templist += tempModuleList[i] + ",";
						}
					}
					if (templist.EndsWith(","))
						templist = templist.Substring(0, templist.Length - 1);
					//将新增的角色添加到用户中去
					if (templist != string.Empty)
					{
						ServiceManager.Instance.UserService.GrantUserModuleScopes(userID, templist, out state, out message);
					}

					templist = string.Empty;

					for (int i = 0; i < moduleList.Length; i++)
					{
						if (!tempModuleList.Contains(moduleList[i]))
						{
							templist += moduleList[i] + ",";
						}
					}
					//移除取消的角色
					if (templist != string.Empty)
					{
						ServiceManager.Instance.UserService.RevokeUserModuleScopes(userID, templist, out state, out message);
					}
				}
			}
			return Json(new CallbackStatus
			{
				message = message,
				statusCode = state,
				callbackType = "closeCurrent"
			});
		}

		/// <summary>
		/// 分配用户的操作权限
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult selectPermission(string id)
		{
			int tempID = 0;
			if (!string.IsNullOrEmpty(id) && int.TryParse(id, out tempID))
			{
				ViewBag.userID = id;
				ViewBag.userName = ServiceManager.Instance.UserService.GetUserEntityByID(tempID).UserName;
				ViewData["permissionListID"] = listToString(ServiceManager.Instance.UserService.GetUserPermissionIds(id));
			}
			else
			{
				ViewBag.userID = string.Empty;
			}
			return View();
		}

		/// <summary>
		/// 设置分配用户的操作权限
		/// </summary>
		/// <returns></returns>
		public ActionResult SetselectPermission()
		{
			string state = "300", message = "设置用户菜单访问权限失败！";
			//全局参数
			string userID = string.Empty, PermissionlistID = string.Empty;
			userID = Request.Params["userID"];
			if (!string.IsNullOrEmpty(userID))
			{
				PermissionlistID = Request.Params["permissionIDs"];
				if (PermissionlistID == null)
					PermissionlistID = string.Empty;
				if (PermissionlistID.EndsWith(","))
					PermissionlistID = PermissionlistID.Substring(0, PermissionlistID.Length - 1);
				string[] Permissionlist = ServiceManager.Instance.UserService.GetUserPermissionIds(userID);//获取该用户所拥有的菜单访问权限               
				if (Permissionlist == null || Permissionlist.Length == 0 && PermissionlistID != string.Empty)
				{
					ServiceManager.Instance.UserService.GrantUserPermissions(userID, PermissionlistID, out state, out message);
				}
				else if (PermissionlistID == string.Empty && Permissionlist.Length > 0)
				{
					ServiceManager.Instance.UserService.RevokeUserPermissions(userID, listToString(Permissionlist), out state, out message);
				}
				else
				{
					string templist = string.Empty;
					string[] tempPermissionlist = PermissionlistID.Split(',');
					//以原角色为参照，比对现有角色
					for (int i = 0; i < tempPermissionlist.Length; i++)
					{
						if (!Permissionlist.Contains(tempPermissionlist[i]))
						{
							templist += tempPermissionlist[i] + ",";
						}
					}
					if (templist.EndsWith(","))
						templist = templist.Substring(0, templist.Length - 1);
					//将新增的角色添加到用户中去
					if (templist != string.Empty)
					{
						ServiceManager.Instance.UserService.GrantUserPermissions(userID, templist, out state, out message);
					}

					templist = string.Empty;

					for (int i = 0; i < Permissionlist.Length; i++)
					{
						if (!tempPermissionlist.Contains(Permissionlist[i]))
						{
							templist += Permissionlist[i] + ",";
						}
					}
					//移除取消的角色
					if (templist != string.Empty)
					{
						ServiceManager.Instance.UserService.RevokeUserPermissions(userID, templist, out state, out message);
					}
				}
			}
			return Json(new CallbackStatus
			{
				message = message,
				statusCode = state,
				callbackType = "closeCurrent"
			});
		}


		/// <summary>
		/// 选择用户签名
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		public ActionResult SelectSigned(int userId)
		{
			Base_User user = ServiceManager.Instance.UserService.GetUserEntityByID(userId);
			return View(user);
		}

		/// <summary>
		/// 上传用户签名
		/// </summary>
		/// <returns></returns>
		public ActionResult UploadSigned(string userId, HttpPostedFileBase FileData)
		{
			//TODO: 处理上传文件类型以及分辨率的控制
			Base_User user = ServiceManager.Instance.UserService.GetUserEntityByID(int.Parse(userId));
			string ext = FileData.FileName.Substring(FileData.FileName.LastIndexOf('.') + 1).ToLower();
			string visualPath = @"/Files/UserSigned/";
			string PhysicalPath = Server.MapPath(visualPath);
			if (!Directory.Exists(PhysicalPath))
			{
				Directory.CreateDirectory(PhysicalPath);
			}

			string fileFullName = user.UserName + "." + ext;
			FileData.SaveAs(PhysicalPath + fileFullName);

			user.SignedPassword = visualPath + fileFullName;
			string statusCode = ""; string msg = "";
			ServiceManager.Instance.UserService.UpdateUser(user, out statusCode, out msg);

			return Json(user);
		}
		/// <summary>
		/// 删除电子签名
		/// </summary>
		/// <param name="uid"></param>
		/// <returns></returns>
		[HttpPost]
		public ActionResult DeletePic(int uid)
		{
			Base_User user = ServiceManager.Instance.UserService.GetUserEntityByID(uid);
			string code = "300";
			string message = "删除失败！";
			try
			{
				if (!string.IsNullOrEmpty(user.SignedPassword))
				{
					string filePath = user.SignedPassword;
					user.SignedPassword = string.Empty;
					ServiceManager.Instance.UserService.UpdateUser(user, out code, out message);
					//删除文件
					filePath = Server.MapPath(filePath);
					if (System.IO.File.Exists(filePath))
						System.IO.File.Delete(filePath);
					code = "200";
					message = "删除成功！";
				}
				else
					message = "该签名文件不存在！";
				
			}
			catch (Exception e)
			{
				message = message + e.Message;
			}

			return Json(new CallbackStatus
			{
				message = message,
				statusCode = code
			});
		}
		/// <summary>
		/// 将数组转化成字符串以指定字符分隔
		/// </summary>
		/// <param name="arry"></param>
		/// <returns></returns>
		private string listToString(string[] arry)
		{
			if (arry == null || arry.Length == 0)
				return string.Empty;
			string s = ",";
			string str = string.Empty;
			for (int i = 0; i < arry.Length; i++)
			{
				str += arry[i] + s;
			}
			return str;
		}

	}

}
